<script setup lang="ts">
import { ref, onUnmounted } from 'vue';

const streamContent = ref<string>('');
const message = ref("");
let eventSource: EventSource | null = null;


const resetState = () => {
  streamContent.value = '';
  eventSource?.close();
};

const startStream = () => {
  resetState();
  const apiUrl = new URL('http://westudy.life:12345/question/streamData');
  apiUrl.searchParams.append('message', message.value);

  eventSource = new EventSource(apiUrl);

  eventSource.onmessage = (event: MessageEvent) => {
    try {
      console.log(event.data);
      if (event.data !== "") {
        if (event.data === "[DONE]") {
          console.log("请求结束");
          eventSource?.close();
          API({
            url: '/question/saveRecord',
            method: 'post',
            data: {
              'question': message.value,
              'ask': streamContent.value
            }
          }).then((res) => {
            console.log("保存结果", res)
          });
          return;
        }
        const map: any = JSON.parse(event.data);
        var delta = map.choices[0].delta;
        var result = delta.reasoning_content || delta.content
        streamContent.value += result;
      }
    } catch (e) {
      console.error('解析错误:', e);
    }
  };
};

onUnmounted(resetState);

</script>

<template>
  <div>
    <el-input v-model="message" placeholder="请输入问题内容" style="margin-top: 10px;"></el-input>
    <el-button type="primary" style="margin: 20px;" @click="startStream">问问小杜</el-button>
    <div class="output">{{ streamContent }}</div>
  </div>
</template>

<style>
.button {
  padding: 0;
  float: right;
  margin-left: 20px;
}

.output {
  white-space: pre-wrap;
  margin: 20px 0;
  padding: 10px;
}
</style>